package com.hzbank.aaronkotlin

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Context
import androidx.fragment.app.FragmentActivity
import com.permissionx.guolindev.PermissionX

//蓝牙工具类
class BlueHelper private constructor(context: Context){


    private val bluetoothManager: BluetoothManager by lazy {
        context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    }

    private val bluetoothAdapter: BluetoothAdapter by lazy {
        bluetoothManager.adapter
    }

    private val bluetoothLeScanner: BluetoothLeScanner by lazy {

        bluetoothManager.adapter.bluetoothLeScanner

    }

    //蓝牙是否可用
    fun blueEnabled(): Boolean{

        return bluetoothAdapter?.isEnabled!!

    }

    //扫描
    @SuppressLint("MissingPermission")
    fun scanBlue(success: (Int, ScanResult?) -> Unit,
                 failed: (Int) -> Unit){

        bluetoothLeScanner.startScan(object : ScanCallback() {

            override fun onScanResult(callbackType: Int, result: ScanResult?) {
                super.onScanResult(callbackType, result)

                success(callbackType, result)
            }

            override fun onScanFailed(errorCode: Int) {
                super.onScanFailed(errorCode)

                failed(errorCode)
            }
        })
    }


    companion object{


        private var blueInstance: BlueHelper? = null

        fun getInstance(context: Context): BlueHelper{
            return blueInstance?: synchronized(this){
                blueInstance?:BlueHelper(context).also { blueInstance = it }
            }

        }
    }
}